package com.shao.channelHandler.watch;

import com.shao.Configuration;
import com.shao.SrpcBootstrap;
import com.shao.loadBalance.LoadBalancer;
import com.shao.utils.network.ChannelAndAddressUtils;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.common.StringUtils;

import java.net.InetSocketAddress;
import java.util.List;

/**
 * @author PaoFu
 * @version 1.0
 * @data 2025/5/14 14:27
 */
@Slf4j
public class UpAndDownWatcher implements Watcher {

    private final Configuration configuration = SrpcBootstrap.getInstance().getConfiguration();

    @Override
    public void process(WatchedEvent event) {
        if (event.getType() == Event.EventType.NodeChildrenChanged) {
            // 子节点发生改变则重新拉取服务列表
            log.warn("服务【{}】的子节点发生了改变，将重新拉取服务列表...", event.getPath());
            String serviceName = getServiceName(event.getPath());
            log.error("serviceName--------------->【{}】", serviceName);
            List<InetSocketAddress> addresses = configuration.getRegistryConfig().getRegistry().lookup(serviceName);
            // 新增
            addresses.forEach(address -> {
                if (!SrpcBootstrap.SOCKET_CHANNEL.containsKey(address)) {
                    Channel channel = ChannelAndAddressUtils.getAvalibleChannel(address);
                    SrpcBootstrap.SOCKET_CHANNEL.put(address, channel);
                }
            });
            // 移除下线的服务
            SrpcBootstrap.SOCKET_CHANNEL.forEach((key, value) -> {
                if (!addresses.contains(key)) {
                    SrpcBootstrap.SOCKET_CHANNEL.remove(key);
                }
            });
            // 重新负载均衡
            LoadBalancer loadBalancer = configuration.getLoadBalancer();
            loadBalancer.reLoadBalancer(serviceName, addresses);
        }
    }

    /**
     * 截取serviceName
     * @param path 路径 《》
     * @return serviceName
     */
    private String getServiceName(String path) {
        if (StringUtils.isBlank(path)) {
            throw new RuntimeException("服务节点为空");
        }
        return path.substring(path.lastIndexOf("/") + 1);
    }
}
